<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <!--<a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="法人标识">
              <j-dict-select-tag placeholder="请选择法人标识" v-model="queryParam.bankNoCd" dictCode="llbb_juridical_person,BANKNAME,ID"/>
            </a-form-item>
          </a-col>-->
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="报表名称">
              <a-input v-model="queryParam.reportname" placeholder="请输入报表名称"></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="数据日期">
              <a-date-picker v-model="queryParam.sjrq" valueFormat="YYYY-MM-DD" />
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-button type="danger" @click="searchQuery" icon="search">查询</a-button>
            <a-button type="danger" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
          </a-col>
        </a-row>
      </a-form>

    </div>
    <!-- 查询区域-END -->
    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button @click="handleVerification('BB_CLWTDK')" type="primary" icon="check-square"
        >校验</a-button
      >
      <a-button @click="handleCheckResult('BB_CLWTDK')" type="primary" icon="download"
        >下载校验结果</a-button
      >
      <a-button @click="handleCommit('BB_CLWTDK')" type="primary" icon="check">提交</a-button>
    </div>
    <!-- table区域-begin -->
    <div>
      <a-table
        ref="table"
        size="middle"
        :scroll="{ x: 1000, y: 340 }"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        class="j-table-force-nowrap"
        @change="handleTableChange"
      >
        <template slot="htmlSlot" slot-scope="text">
          <div v-html="text"></div>
        </template>
        <template slot="imgSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px; font-style: italic">无图片</span>
          <img
            v-else
            :src="getImgView(text)"
            height="25px"
            alt=""
            style="max-width: 80px; font-size: 12px; font-style: italic"
          />
        </template>
        <template slot="fileSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px; font-style: italic">无文件</span>
          <a-button v-else :ghost="true" type="primary" icon="download" size="small" @click="downloadFile(text)">
            下载
          </a-button>
        </template>

        <span slot="action" slot-scope="text, record">
          <!-- <a @click="handleEdit(record)">编辑</a> -->
          <a
            :href="`/websheet/api?parameter=${Base.encode(
              `bbdm:${record.bbdm}&bbpc:${record.bbpc}&ssjg:${record.ssjg}&frdm:${record.bankNoCd}&type:render&readonly:0`
            )}`"
            target="_blank"
            v-if="record.commitStatus !== '3'"
          >
            修改
          </a>
          <a
            :href="`/websheet/api?parameter=${Base.encode(
              `bbdm:${record.bbdm}&bbpc:${record.bbpc}&ssjg:${record.ssjg}&frdm:${record.bankNoCd}&type:render&readonly:1`
            )}`"
            target="_blank"
            v-if="record.commitStatus === '3'"
          >
            查看
          </a>
        </span>
      </a-table>
    </div>

    <llbb-report-status-modal ref="modalForm" @ok="modalFormOk"></llbb-report-status-modal>
    <!-- <HandelCheckModal ref="handelCheck" @ok="modalFormOk"></HandelCheckModal> -->

    <j-modal
      :visible.sync="modal.visible"
      :width="600"
      :title="modal.title"
      :fullscreen.sync="modal.fullscreen"
      :switchFullscreen="modal.switchFullscreen"
    >
      <p v-for="(i, k) in dataList" :key="k">{{ i }}</p>
    </j-modal>
    <j-modal
      :visible.sync="jmodal.visible"
      :width="600"
      :title="jmodal.title"
      :fullscreen.sync="jmodal.fullscreen"
      :switchFullscreen="jmodal.switchFullscreen"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <a-textarea
        v-model="jmodal.reason"
        placeholder="请输入退回原因"
        maxLength="2000"
        :auto-size="{ minRows: 6, maxRows: 12 }"
      />
    </j-modal>
  </a-card>
</template>

<script>
import '@/assets/less/TableExpand.less'
import { mixinDevice } from '@/utils/mixin'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import LlbbReportStatusModal from './modules/LlbbReportStatusModal'
import { getAction, httpAction, downFile } from '@/api/manage'
import JSelectDepart from '@/components/jeecgbiz/JSelectDepart'
import { mapGetters } from 'vuex'
import { getMetaList } from '@/api/websheet'
import { Base } from '@/views/websheet/luckysheet/utils/utils.js'
// import HandelCheckModal from '../../bulu/checkData/HandelCheckModal.vue'

export default {
  name: 'LlbbReportStatusList',
  mixins: [JeecgListMixin, mixinDevice],
  components: {
    LlbbReportStatusModal,
    JSelectDepart,
    // HandelCheckModal,
  },
  data() {
    return {
      Base,
      interval: 0,
      metaList: [],
      isShowResult: false,
      isResult: false,
      jyInfo: '',
      modal: {
        title: '信息提示',
        visible: false,
        fullscreen: false,
        switchFullscreen: false,
      },
      jmodal: {
        title: '信息提示',
        visible: false,
        fullscreen: false,
        switchFullscreen: false,
        ids: '',
        reason: '',
      },
      dataList: [],
      description: '报表状态表管理页面',
      // 表头
      columns: [
        {
          title: '选项',
          dataIndex: '',
          key: 'rowIndex',
          width: 50,
          align: 'center',
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          },
        },
        {
          title: '报表名称',
          align: 'center',
          dataIndex: 'reportname',
        },
        {
          title: '数据日期',
          align: 'center',
          dataIndex: 'sjrq',
          customRender: function (text) {
            return !text ? '' : text.length > 10 ? text.substr(0, 10) : text
          },
        },
        {
          title: '报送频度',
          align: 'center',
          dataIndex: 'bspd_dictText',
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          fixed: 'right',
          width: 147,
          scopedSlots: { customRender: 'action' },
        },
      ],
      url: {
        list: '/reportstatus/llbbReportStatus/rspclist',
        delete: '/reportstatus/llbbReportStatus/delete',
        deleteBatch: '/reportstatus/llbbReportStatus/deleteBatch',
        exportXlsUrl: '/reportstatus/llbbReportStatus/exportXls',
        importExcelUrl: 'reportstatus/llbbReportStatus/importExcel',
        Batchcheck: '/reportstatus/llbbReportStatus/batchcheck',
        BatchSubmit: '/reportstatus/llbbReportStatus/batchSubmit',
        SubmitReturn: '/reportstatus/llbbReportStatus/submitReturn',
        batchAuditing: '/reportstatus/llbbReportStatus/batchAuditing',
        AuditingReturn: '/reportstatus/llbbReportStatus/auditingReturn',
      },
      dictOptions: {},
      superFieldList: [],
    }
  },
  created() {
    this.getSuperFieldList()
    getMetaList({ pageSize: 1000, bbfl: '1' }).then((res) => {
      if (res.code === 200) {
        this.metaList = res.result.records || []
      } else {
        this.$message.warning('服务器出错!')
      }
    })
  },
  computed: {
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    },
  },
  methods: {
    localhandleExportXls(fileName) {
      if (!fileName || typeof fileName != 'string') {
        fileName = '导出文件'
      }
      let param = this.getQueryParams()
      if (this.selectedRowKeys && this.selectedRowKeys.length > 0) {
        param['selections'] = this.selectedRowKeys.join(',')
      }
      let downloadUrl = this.url.exportXlsUrl
      downFile(downloadUrl, param).then((data) => {
        if (!data) {
          this.$message.warning('文件下载失败')
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data], { type: 'application/vnd.ms-excel' }), fileName + '.xlsx')
        } else {
          let url = window.URL.createObjectURL(new Blob([data], { type: 'application/vnd.ms-excel' }))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName + '.xlsx')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link) //下载完成移除元素
          window.URL.revokeObjectURL(url) //释放掉blob对象
        }
      })
    },
    ...mapGetters(['nickname', 'avatar', 'userInfo']),
    handleOk() {
      if (typeof this.jmodal.reason == 'undefined' || this.jmodal.reason == '') {
        this.$message.warning('请填写退回原因')
        return
      }
      var that = this
      that.loading = true
      getAction(that.url.SubmitReturn, { ids: this.jmodal.ids, reason: this.jmodal.reason })
        .then((res) => {
          if (res.success) {
            that.$message.success(res.message)
            that.loadData()
            that.onClearSelected()
            that.jmodal.ids = ''
            that.jmodal.reason = ''
          } else {
            that.$message.warning(res.message)
          }
        })
        .finally(() => {
          that.loading = false
        })
    },
    handleCancel() {
      this.jmodal.visible = false
    },
    showResult() {
      this.modal.visible = true
    },
    allDataCheck() {
      let that = this
      if (this.queryParam.sjrq == undefined || this.queryParam.sjrq == '') {
        this.$message.warning('请选择数据日期')
        return
      }
      this.$confirm({
        title: '批量表间校验',
        content: '确认批量表间校验?',
        onOk: function () {
          that.dataList = []
          that.isResult = true
          that.isShowResult = false
          that.jyInfo = '正在校验' + that.queryParam.sjrq + '日数据'
          that.interval = self.setInterval(that.checkInterval, 500)
          httpAction('/messagemanagement/report/allDataCheck', { sjrq: that.queryParam.sjrq }, 'POST').then((res) => {
            window.clearInterval(that.interval)
            if (res.success) {
              that.jyInfo = '校验成功，数据无误'
            } else {
              if (res.result == null) {
                that.jyInfo = res.message
              } else {
                that.jyInfo = '校验完毕,数据有误'
                that.isShowResult = true
                that.dataList = res.result
              }
            }
          })
        },
      })
    },
    checkInterval() {
      httpAction('/messagemanagement/report/check', { sjrq: this.queryParam.sjrq }, 'POST').then((res) => {
        if (res.success) {
          this.jyInfo = '校验成功，数据无误'
          window.clearInterval(this.interval)
        } else {
          if (res.result == null) {
            if (res.message != 'no') {
              this.jyInfo = res.message
              window.clearInterval(this.interval)
            }
          } else {
            this.jyInfo = '校验完毕,数据有误'
            this.isShowResult = true
            this.dataList = res.result
            window.clearInterval(this.interval)
          }
        }
      })
    },
    initDictConfig() {},
    getSuperFieldList() {
      let fieldList = []
      fieldList.push({ type: 'string', value: 'bankNoCd', text: '法人标识' })
      fieldList.push({
        type: 'string',
        value: 'devideCls',
        text: '权限划分类别。按固定依据划分数据权限：1-角色2-机构3-用户',
      })
      fieldList.push({ type: 'string', value: 'bankCode', text: '分支机构编码' })
      fieldList.push({ type: 'string', value: 'reportId', text: '报表记录id' })
      fieldList.push({ type: 'string', value: 'dataStatus', text: '数据状态。1-未生成2-已生成有误3-已生成成功' })
      fieldList.push({ type: 'string', value: 'verifyStatus', text: '校验状态。1-未校验2-已校验有误3-已校验无误' })
      fieldList.push({ type: 'string', value: 'commitStatus', text: '提交状态。1-未提交2-已打回3-已提交' })
      fieldList.push({ type: 'string', value: 'auditStatus', text: '审核状态。1-未审核2-审核打回3-审核通过' })
      this.superFieldList = fieldList
    },
    Batchcheck() {
      if (!this.url.Batchcheck) {
        this.$message.error('请设置url.Batchcheck属性!')
        return
      }
      if (this.selectionRows.length <= 0) {
        this.$message.warning('请选择一条记录！')
        return
      } else {
        var ids = ''
        let dataSjrq = []
        let orgCode = []
        let tableCode = {}
        for (var a = 0; a < this.selectionRows.length; a++) {
          dataSjrq[a] = this.selectionRows[a].sjrq
          orgCode[a] = this.selectionRows[a].sysOrgCode
          tableCode[a] = this.selectionRows[a].reportId

          ids += this.selectionRows[a].id + ','
          if (this.selectionRows[a].verifyStatus == '3') {
            this.$message.warning('已校验数据不可重复校验！')
            return
          }
        }
        let paraData = {
          sjrq: dataSjrq,
          orgCode: orgCode,
          tableCode: tableCode,
        }
        var that = this
        this.$confirm({
          title: '确认校验',
          content: '是否校验选中数据?',
          onOk: function () {
            that.loading = true
            getAction(that.url.Batchcheck, { ids: ids })
              .then((res) => {
                if (res.success) {
                  that.$message.success(res.message)
                  that.loadData()
                  that.onClearSelected()
                } else {
                  that.$message.warning(res.message)
                }
              })
              .finally(() => {
                that.loading = false
              })
          },
        })
      }
    },
    BatchSubmit() {
      if (!this.url.BatchSubmit) {
        this.$message.error('请设置url.BatchSubmit属性!')
        return
      }
      if (this.selectionRows.length <= 0) {
        this.$message.warning('请选择一条记录！')
        return
      } else {
        var ids = ''
        for (var a = 0; a < this.selectionRows.length; a++) {
          ids += this.selectionRows[a].id + ','
          if (this.selectionRows[a].verifyStatus != '3') {
            this.$message.warning('未校验成功数据不能提交！')
            return
          }
          if (this.selectionRows[a].commitStatus == '3') {
            this.$message.warning('已提交数据不能提交！')
            return
          }
        }
        var that = this
        this.$confirm({
          title: '确认提交',
          content: '是否提交选中数据?',
          onOk: function () {
            that.loading = true
            getAction(that.url.BatchSubmit, { ids: ids })
              .then((res) => {
                if (res.success) {
                  that.$message.success(res.message)
                  that.loadData()
                  that.onClearSelected()
                } else {
                  that.$message.warning(res.message)
                }
              })
              .finally(() => {
                that.loading = false
              })
          },
        })
      }
    },
    SubmitReturn() {
      if (!this.url.SubmitReturn) {
        this.$message.error('请设置url.Batchcheck属性!')
        return
      }
      if (this.selectionRows.length <= 0) {
        this.$message.warning('请选择一条记录！')
        return
      } else {
        var ids = ''
        for (var a = 0; a < this.selectionRows.length; a++) {
          ids += this.selectionRows[a].id + ','
          if (this.selectionRows[a].commitStatus != '3') {
            this.$message.warning('未提交数据不能打回！')
            return
          }
          /* if (this.selectionRows[a].auditStatus != "2") {
              this.$message.warning('未审批打回不能提交打回！');
              return;
            }
            if (this.selectionRows[a].dataStatus == "3") {
              this.$message.warning('报文已生成不能打回！');
              return;
            }*/
        }
        const that = this
        that.jmodal.visible = true
        that.jmodal.ids = ids
      }
    },
    batchAuditing() {
      if (!this.url.batchAuditing) {
        this.$message.error('请设置url.Batchcheck属性!')
        return
      }
      if (this.selectionRows.length <= 0) {
        this.$message.warning('请选择一条记录！')
        return
      } else {
        var ids = ''
        for (var a = 0; a < this.selectionRows.length; a++) {
          ids += this.selectionRows[a].id + ','
          if (this.selectionRows[a].commitStatus != '3') {
            this.$message.warning('未提交数据不能审批通过！')
            return
          }
          if (this.selectionRows[a].auditStatus == '3') {
            this.$message.warning('已审批通过不能重复操作！')
            return
          }
          if (this.selectionRows[a].dataStatus == '3') {
            this.$message.warning('报文已生成不能打回！')
            return
          }
        }
        var that = this
        this.$confirm({
          title: '审批通过',
          content: '是否审批通过选中数据?',
          onOk: function () {
            that.loading = true
            getAction(that.url.batchAuditing, { ids: ids })
              .then((res) => {
                if (res.success) {
                  that.$message.success(res.message)
                  that.loadData()
                  that.onClearSelected()
                } else {
                  that.$message.warning(res.message)
                }
              })
              .finally(() => {
                that.loading = false
              })
          },
        })
      }
    },

    AuditingReturn() {
      if (!this.url.AuditingReturn) {
        this.$message.error('请设置url.Batchcheck属性!')
        return
      }
      if (this.selectionRows.length <= 0) {
        this.$message.warning('请选择一条记录！')
        return
      } else {
        var ids = ''
        for (var a = 0; a < this.selectionRows.length; a++) {
          ids += this.selectionRows[a].id + ','
          if (this.selectionRows[a].auditStatus != '3') {
            this.$message.warning('未审批通过不能打回！')
            return
          }
        }
        var that = this
        this.$confirm({
          title: '确认打回',
          content: '是否打回选中数据?',
          onOk: function () {
            that.loading = true
            getAction(that.url.AuditingReturn, { ids: ids })
              .then((res) => {
                if (res.success) {
                  that.$message.success(res.message)
                  that.loadData()
                  that.onClearSelected()
                } else {
                  that.$message.warning(res.message)
                }
              })
              .finally(() => {
                that.loading = false
              })
          },
        })
      }
    },
  },
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>